<?php

// Visibility tables
$tbl_mdb_names = claro_sql_get_main_tbl();
$tbl_UDADOCdocumentVisibilityPeriod = claro_sql_get_tbl('UDADOCdocumentVisibilityPeriod');
$tbl_UDADOCdocumentVisibilityPeriod = $tbl_UDADOCdocumentVisibilityPeriod['UDADOCdocumentVisibilityPeriod'];

$tbl_UDADOCrelClassPeriod = claro_sql_get_tbl('UDADOCrelClassPeriod');
$tbl_UDADOCrelClassPeriod = $tbl_UDADOCrelClassPeriod['UDADOCrelClassPeriod'];


require_once get_path('incRepositorySys')  . '/lib/class.lib.php';

require_once 'UDADOCfileUpload.lib.php';

/**
     * Retourne la p�riode de disponibilit� pour un document donn�
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $course_code, varchar $file (chemin du document)
     * @return array() timestamp des dates de d�but et de fin
     */

function UDADOCcheckVisibilityDates($course_code, $file)
{
	global $tbl_UDADOCdocumentVisibilityPeriod;
	global $tbl_UDADOCrelDocPeriod;
	
	$document_id = UDADOCgetDocumentId($file);

	if (!$document_id)
	return false;

	$sql = "SELECT id,unix_timestamp(visibilityStartDate)  as `visibilityStartDate`, 
		       unix_timestamp(visibilityEndDate) as `visibilityEndDate`,
			   allUsers
			FROM `".$tbl_UDADOCdocumentVisibilityPeriod."`
			WHERE course_code = '".$course_code."'
			AND documentId = ".$document_id."
			ORDER BY visibilityStartDate";

	$visibilityDatesList = claro_sql_query_fetch_all_rows($sql);

	return $visibilityDatesList;
}


/**
     * Retourne si le document est visible actuellement ou non
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $course_code, varchar $file (chemin du document)
     * @return boolean
     */

function UDADOCisDocumentVisibleNow($course_code, $file, $userId)
{
	$visibilityDatesList = UDADOCcheckVisibilityDates($course_code, $file);
	
	// Get user classes
	$userClasses = array();
	$userClasses = UDADOCgetUserClasses($userId);
	
	foreach ($visibilityDatesList as $period)
	{
		if ($period['allUsers'] == 0)
		{
			// Skip period if the user is not in the right class
			$selectedClasses = UDADOCgetSelectedClasses($period['id']);
			
			foreach ($selectedClasses['class_id'] as $class)
			{
				if (in_array($class,$userClasses))
				{
					if ($period['visibilityStartDate'] <= mktime() && $period['visibilityEndDate'] >= mktime())
					{
						return true;
						break;
					}
				}
			}
		}
		else
		{
			if ($period['visibilityStartDate'] <= mktime() && $period['visibilityEndDate'] >= mktime())
			return true;
		}
	}
	
	return false;
}


/**
     * Retourne si le document est visible actuellement ou non
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $course_code, varchar $file (chemin du document)
     * @return boolean
     */
function UDADOCisAnyDocumentWithDates ($course_code)
{
	global $dbTable;
	$sql = "SELECT `path`
                FROM `".$dbTable."`
		LEFT JOIN `cl_UDADOCdocumentVisibilityPeriod`
		ON `".$dbTable."`.id = `cl_UDADOCdocumentVisibilityPeriod`.document_id
		WHERE course_code = '".$course_code."'";

	$pathList = claro_sql_query_fetch_all_cols($sql);
	
	if ($pathList)
	{
		foreach ($pathList[path] as $chemin)
		{
			if (UDADOCisDocumentVisibleNow($course_code, $chemin))
			return true;
		}
	}
	return false;
}


/**
     * Ins�re une p�riode de visibilit�
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $course_code, varchar $file (chemin du document), timestamp $visibilityStartDate, timestamp $visibilityStartDate
     * @return boolean
     */

function UDADOCsetVisibilityPeriod ($course_code, $file, $visibilityStartDate, $visibilityEndDate)
{
	$document_id = UDADOCgetDocumentId($file);

	if (!$document_id)
	{
		// On cr�� une entr�e dans les documents du cours
		update_db_info('update', $file,
                                        array('visibility' => 'i' ) );
		$document_id = UDADOCgetDocumentId($file);
	}

	// L'entr�e existe, on fait un update
	if (UDADOCcheckVisibilityDates($course_code,$file))
	{
		$sql = "UPDATE cl_UDADOCdocumentVisibilityPeriod
			SET visibilityStartDate = FROM_UNIXTIME(".$visibilityStartDate."),
			visibilityEndDate = FROM_UNIXTIME(".$visibilityEndDate.")
			WHERE course_code = '".$course_code."'
			AND document_id = ".$document_id;
		claro_sql_query($sql);
	}
	else
	{
			$sql = "INSERT INTO cl_UDADOCdocumentVisibilityPeriod
				SET visibilityStartDate = FROM_UNIXTIME(".$visibilityStartDate."),
				visibilityEndDate = FROM_UNIXTIME(".$visibilityEndDate."),
				course_code = '".$course_code."',
				document_id = ".$document_id;
			claro_sql_query($sql);
	}

	return true;
}



/**
     * Cherche l'id d'un document
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $path (chemin du document)
     * @global $dbTable
     * @return integer
     */

function UDADOCgetDocumentId($path)
{
	$courseTblList = claro_sql_get_course_tbl();
        $tbl_document =  $courseTblList['document'];

	$sql = "SELECT `id`
                FROM `".$tbl_document."`
                WHERE path = '".$path."'";
        $doc_id = claro_sql_query_get_single_value($sql);

	return $doc_id;
}


/**
     * Supprime les p�riodes des documents pr�sent dans un r�pertoire
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $course_code, varchar $path (chemin du document)
     * @global $dbTable
     * @return true
     */

function UDADOCdeleteFilesInDirectory($course_code, $file)
{
	global $dbTable;
	$sql = "SELECT `path`
                FROM `".$dbTable."`
                WHERE path LIKE '".$file."/%'";
        $fileList = claro_sql_query_fetch_all_cols($sql);
	foreach ($fileList[path] as $deleteFile)
	{
		UDADOCunsetVisibilityPeriod ($course_code, $deleteFile);
	}
}

/**
 * Get the list of invisible documents of the current course
 *
 * @param $baseWorkDir path document
 * @param $cidReq course identifier
 * @return list of invisible document
 */

function UDADOCgetInvisibleDocumentList ( $baseWorkDir, $cidReq = null )
{
    $documentList = array();

    if ( is_null($cidReq) ) $cid = claro_get_current_course_id() ;
    else                    $cid = $cidReq ;

    $tbl_cdb_names = claro_sql_get_course_tbl(claro_get_course_db_name_glued($cid));
    $tbl_document = $tbl_cdb_names['document'];

    $sql = "SELECT path
            FROM `". $tbl_document ."`
            WHERE visibility = 'i'";

    $documentList = claro_sql_query_fetch_all_cols($sql);
    $documentList = $documentList['path'];

    for( $i=0; $i < count($documentList); $i++ )
    {
	 // CLFD Rend le doc visible (invisible par d�faut pour dr�er une entr�e dans la db)
	 // en cas de p�riode de visibilit�
	 if (UDADOCisDocumentVisibleNow($cid, $documentList[$i],claro_get_current_user_id()))
	 unset($documentList[$i]);

        $documentList[$i] = $baseWorkDir.$documentList[$i];
    }

    return $documentList ;
}


/**
     * Delete an item (document or directory)
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $fileToDelete,$baseWorkDir,$courseContext
     * @return boolean
     */

function UDADOCremoveItem($fileToDelete,$baseWorkDir,$courseContext)
{
	        $file = secure_file_path($fileToDelete);
	        
	        $contenuFichier = file_get_contents($baseWorkDir.$file);
	       
	       // Découpage de la chaine pour vérifier s'il s'agit d'un fichier Elgg
	       $chercher = get_conf('elggWebservice').'?action=read&file_guid=';
	       $chercher = preg_quote($chercher, '\\');

	       preg_match('('.$chercher.'[0-9]+)', $contenuFichier, $matches);
	       
	       if ($matches)
	       {
	       	$guid = substr($matches[0],strrpos($matches[0],'=')+1);
	       	
	       	$listeLiens = array('cours'=>claro_get_current_course_id(),'objets'=>array($guid));
				$listeLiens = json_encode($listeLiens);
	       	
	       	require_once get_path('incRepositorySys') . '/lib/user.lib.php';
    			$infosUser = user_get_properties(claro_get_current_user_id());
    			
	       	$feedback = file_get_contents(get_conf('elggWebservice')."?action=supprimerLiensObjetPlateformeCours&referer=".get_path('rootWeb')."&user=".$infosUser['username']."&listeLiens=".$listeLiens);

	       }

		if ( claro_delete_file($baseWorkDir.$file))
		{
		    if ($courseContext)
		    {
			update_db_info('delete', $file);
			update_Doc_Path_in_Assets('delete', $file, '');
		    }

		    //notify that a document has been deleted
		    global $eventNotifier;
		    $eventNotifier->notifyCourseEvent("document_file_deleted",claro_get_current_course_id(), claro_get_current_tool_id(),$fileToDelete, claro_get_current_group_id(), "0");

		    return true;
		}

		return false;
}


/**
     * Move an item (document or directory)
     *
     * @author Pierre Raynaud <pierre.raynaud@u-clermont1.fr>
     * @param varchar $fileToMove,$baseWorkDir,$courseContext
     * @return boolean
     */
function UDADOCmoveItem($fileToMove,$baseWorkDir,$courseContext,$ajaxContext=false)
{
		global $eventNotifier;
	
		$fileToMove = secure_file_path( $fileToMove);
        $_REQUEST['destination'] = secure_file_path( $_REQUEST['destination']);

        if ( UDADOCclaro_move_file($baseWorkDir.$fileToMove,$baseWorkDir.$_REQUEST['destination']) )
        {
            if ($courseContext)
            {
                update_db_info( 'update', $fileToMove,
                                array('path' => $_REQUEST['destination'].'/'.basename($fileToMove)) );
                update_Doc_Path_in_Assets("update",$fileToMove,
                                                   $_REQUEST['destination'].'/'.basename($fileToMove));
            }
            $ressource['old_uri'] = $fileToMove;
            $ressource['new_uri'] = $_REQUEST['destination'].'/'.basename($fileToMove);
            $eventNotifier->notifyCourseEvent('document_moved', claro_get_current_course_id(), claro_get_current_tool_id(), $ressource, claro_get_current_group_id(), '0');

			if ($ajaxContext == false)
            $dialogBox = get_lang('Element moved').'<br />';
			else
			return true;
        }
        else
        {
            $dialogBox = get_lang('Operation impossible').'<br />';

            if ( claro_failure::get_last_failure() == 'FILE EXISTS' )
            {
                $dialogBox .= get_lang('A file with the name %name already exists in the target folder.',array('%name'=>"<i>".basename($fileToMove)."</i>"));
            }
            elseif (claro_failure::get_last_failure() == 'MOVE INSIDE ITSELF')
            {
                $dialogBox .= get_lang('You cannot move the element %name inside itself.',array('%name'=>"<i>".basename($fileToMove)."</i>"));
            }

        }
	
		return $dialogBox;
}

function UDADOCclaro_move_file($sourcePath, $targetPath)
{	
    //if (realpath($sourcePath) == realpath($targetPath) ) return true;

    // check to not copy a directory inside itself
    if (   is_dir($sourcePath)
        && ereg('^' . $sourcePath . '/', $targetPath . '/') )
        return claro_failure::set_failure('MOVE INSIDE ITSELF');

    $sourceFileName = basename($sourcePath);

    if (   $sourcePath == $targetPath
        || file_exists($targetPath . '/' . $sourceFileName) )
         return claro_failure::set_failure('FILE EXISTS');

    if ( is_dir($targetPath) )
    {
        return rename($sourcePath, $targetPath . '/' . $sourceFileName);
    }
    else
    {
        return rename($sourcePath, $targetPath);
    }
}


function UDADOCupdateVisFile($file,$vis)
{
	global $eventNotifier;
	
	$file = secure_file_path($file);

    update_db_info('update', $file, array('visibility' => $vis) );

    $dialogBox = get_lang("Visibility modified");

    //notify claroline that visibility changed

    if ($vis == 'v')
    {
        $eventNotifier->notifyCourseEvent("document_visible",claro_get_current_course_id(), claro_get_current_tool_id(), $file, claro_get_current_group_id(), "0");
    }
    else
    {
        $eventNotifier->notifyCourseEvent("document_invisible",claro_get_current_course_id(), claro_get_current_tool_id(), $file, claro_get_current_group_id(), "0");
    }
	
	return $dialogBox;
}


function UDADOCclass_get_properties ( $classId )
{
    $tbl = claro_sql_get_main_tbl();

    $sql = "SELECT id,
                   name,
                   class_parent_id,
                   class_level,
				   description
            FROM `" . $tbl['class'] . "`
            WHERE `id`= ". (int) $classId ;

    $result = claro_sql_query_get_single_row($sql);

    if ( $result ) return $result;
    else           return claro_failure::set_failure('class_not_found');
}

function UDADOCget_class_list_by_course($courseId)
{
    $tbl = claro_sql_get_main_tbl();

    $sql = "
        SELECT C.id AS `id`
        FROM `" . $tbl['class'] . "` C, `" . $tbl['rel_course_class'] . "` CC
        WHERE CC.`classId` = C.`id`
        AND CC.`courseId` = '" . addslashes($courseId) . "'
        ORDER BY C.`name`";
    return claro_sql_query_fetch_all($sql);
}


function UDADOCgetSelectedClasses($periodId)
{
	global $tbl_UDADOCrelClassPeriod;
	
	$sql = "SELECT class_id FROM `".$tbl_UDADOCrelClassPeriod."` WHERE period_id = ".$periodId;
	return claro_sql_query_fetch_all_cols($sql);
}



function UDADOCdisplayVisDatesForm($_cid,$file=false)
{
	global $dateTimeFormatShort;
	
	// Beforehand, we must set the visibility to hidden or else we won't be able to get a document id
	UDADOCupdateVisFile($file,"i");
	
	
	if ($_REQUEST['ajax'])
	$dialogBox .= "<strong>".get_lang('Visibility periods for the selected files')."</strong>";
	else
	$dialogBox .= "<strong>".get_lang('Visibility periods for the file')." : ".substr($file,1).'</strong>';
	
	$dialogBox .= "<hr>";
	
	$visibilityDates = UDADOCcheckVisibilityDates($_cid, $file);
	
	if (!$visibilityDates)
	$dialogBox .= "<i>".get_lang('No visibility period is defined')."</i>";
	else
	{
		$dialogBox .= "<ul id='UDADOCperiods'><form>";
		
		foreach ($visibilityDates as $dates)
		{
			if ($dates['visibilityStartDate'] <= mktime() && $dates['visibilityEndDate'] >= mktime())
			$img = 'visible.gif';
			else
			$img = 'invisible.gif';
			
			$dialogBox .= "<li id='period_".$dates['id']."'>
								<img src='".get_path('imgRepositoryWeb').$img."'> 
								<span class='visDates'>".get_lang('Visible from %dateFrom to %dateTo',array('%dateFrom'=>'<span class="visStartDate">'.claro_disp_localised_date($dateTimeFormatShort,$dates['visibilityStartDate']).'</span>','%dateTo'=>'<span class="visEndDate">'.claro_disp_localised_date($dateTimeFormatShort,$dates['visibilityEndDate'])."</span>")).'</span> 
							<img alt="'.get_lang('Modify').'" src="'.get_path('imgRepositoryWeb').'edit.gif" class="editDates"/>
							<img alt="'.get_lang('Delete').'" src="'.get_path('imgRepositoryWeb').'delete.gif" class="deleteDates"/><br>';
			
			// Only for the selected classes
			$selectedClasses = UDADOCgetSelectedClasses($dates['id']);
			
			if ($dates['allUsers'] == 1)
			{
				$allUsersChecked = "checked = 'checked'";
				$filterUsersChecked = "";
				$displayAll = "none";
			}
			else
			{
				$allUsersChecked = "";
				$filterUsersChecked = "checked = 'checked'";
				$displayAll = "block";
			}
			
			
			$dialogBox .= "<div><input type='radio' name='UDADOCfilter_".$dates['id']."' value='all' ".$allUsersChecked.">".get_lang('For everyone in this course');
			
			$classList = UDADOCget_class_list_by_course($_cid);
			
			if ($classList)
			{
				$dialogBox .= "<br><input type='radio' name='UDADOCfilter_".$dates['id']."' value='' ".$filterUsersChecked.">".get_lang('Only for the members of the following classes')."
								<a href='javascript:' class='UDADOCshowHide' style='display:".$displayAll.";'>".get_lang('Show / hide classes')."</a>
								<ul style='display:none;'>";
				
				foreach ($classList as $class)
				{
					if (in_array($class['id'],$selectedClasses['class_id']))
					$checked = "checked = 'checked'";
					else
					$checked = "";
					
					
					$classInfos = UDADOCclass_get_properties ( $class['id'] );
					$dialogBox .= "<li><input type='checkbox' value='".$class['id']."' ".$checked."> ".$classInfos['name']." : ".$classInfos['description']."</li>";
				}
				
				$dialogBox .= "</ul>";	
			}
			else
			{
				$dialogBox .= "<br><input type='radio' disabled='disabled' name='UDADOCfilter_".$dates['id']."' value='' ".$filterUsersChecked.">".get_lang('Only for the members of the following classes')."
								<br>
								<i>".get_lang('No class registered to this course')."</i>";
			}
			
			$dialogBox .= "</li>";
		}
		
		$dialogBox .= '</ul></div></form>';
	}
	
	$dialogBox .= '<br><a href="javascript:;" id="UDADOCnewPeriod"><img src="'.get_path('imgRepositoryWeb').'agenda.gif" border="0" alt="'.get_lang('New period').'">'.get_lang('New period').'</a>';
	
	
	// Add the date selector box
	$dialogBox .= '<div id="changeDatesBox" class="jqmWindow claroMessageBox">
			<input type="hidden" id="periodModified" value="">
			<input type="hidden" id="documentId" value="'.UDADOCgetDocumentId($file).'">
			<table>
				<tr class="headerX">
					<th><a href="#" class="jqmClose"><img src="css/images/close.png" alt="'.get_lang('Close').'"></a></th>
				</tr>
				<tr>
					<td>
						'.get_lang('Start date').' : <br>
							<input type="text" value="" id="startDate" readonly="readonly">
							<select id="startHours">';
							
							for ($i=0;$i<24;$i++)
							{
								if ($i<10)
								$val = "0".$i;
								else
								$val = $i;
								
								$dialogBox .= '<option value="'.$val.'">'.$val.'</option>';
							}	
							
			 $dialogBox .= '</select> : 
			 				<select id="startMinutes">';
							for ($i=0;$i<60;$i++)
							{
								if ($i<10)
								$val = "0".$i;
								else
								$val = $i;
								
								$dialogBox .= '<option value="'.$val.'">'.$val.'</option>';
							}
	$dialogBox .= '</select>
						<br><br>
						'.get_lang('End date').' : <br>
							<input type="text" value="" id="endDate" readonly="readonly">
							<select id="endHours">';
							
							for ($i=0;$i<24;$i++)
							{
								if ($i<10)
								$val = "0".$i;
								else
								$val = $i;
								
								$dialogBox .= '<option value="'.$val.'">'.$val.'</option>';
							}	
							
			 $dialogBox .= '</select> : 
			 				<select id="endMinutes">';
							for ($i=0;$i<60;$i++)
							{
								if ($i<10)
								$val = "0".$i;
								else
								$val = $i;
								
								$dialogBox .= '<option value="'.$val.'">'.$val.'</option>';
							}
	$dialogBox .= '</select>
						<br>
						<br>
						<button>'.get_lang('OK').'</button> <button>'.get_lang('Cancel').'</button>
					</td>
				</tr>
			</table>
		</div>';
				  
	return $dialogBox;
}


function UDADOCeditVisibilityPeriod($periodId,$startDate,$endDate,$documentId)
{
	global $tbl_UDADOCdocumentVisibilityPeriod;
	
	if ($periodId == 'new')
	{
		$sql = "INSERT INTO `".$tbl_UDADOCdocumentVisibilityPeriod."` 
				SET visibilityStartDate = '".$startDate."',
					visibilityEndDate = '".$endDate."',
					course_code = '".claro_get_current_course_id()."',
					allUsers = 1,
					documentId = ".$documentId;
	}
	else
	{
		$sql = "UPDATE `".$tbl_UDADOCdocumentVisibilityPeriod."` 
				SET visibilityStartDate = '".$startDate."',
					visibilityEndDate = '".$endDate."'
				WHERE id = ".$periodId;		
	}

	return claro_sql_query($sql);
}

function UDADOCdeleteVisibilityPeriod($periodId)
{
	global $tbl_UDADOCdocumentVisibilityPeriod;
	global $tbl_UDADOCrelClassPeriod;
	
	$sql = "DELETE FROM `".$tbl_UDADOCdocumentVisibilityPeriod."` WHERE id = ".$periodId;
	$sqlEXE = claro_sql_query($sql);
	
	$sql = "DELETE FROM `".$tbl_UDADOCrelClassPeriod."` WHERE period_id = ".$periodId;
	
	if($sqlEXE)
	$sqlEXE = claro_sql_query($sql);
	else
	claro_sql_query($sql);
	
	return $sqlEXE;
}

function UDADOCeditVisAccess($periodId,$allUsers)
{
	global $tbl_UDADOCdocumentVisibilityPeriod;
	$sql = "UPDATE `".$tbl_UDADOCdocumentVisibilityPeriod."` 
			SET allUsers = '".$allUsers."'
			WHERE id = ".$periodId;
	return claro_sql_query($sql);
}

function UDADOCeditVisClass($periodId,$class,$visible=0)
{
	global $tbl_UDADOCrelClassPeriod;
	
	if ($visible == 1)
	{
		$sql = "INSERT INTO `".$tbl_UDADOCrelClassPeriod."` 
				SET period_id = ".$periodId.",
				    class_id = ".$class;
	}
	else
	{
		$sql = "DELETE FROM `".$tbl_UDADOCrelClassPeriod."` 
				WHERE period_id = ".$periodId."
				AND class_id = ".$class;
	}
	
	return claro_sql_query($sql);
}

function UDADOCgetUserClasses($userId)
{
	$tbl = claro_sql_get_main_tbl();
	$sql = "SELECT class_id
            FROM `".$tbl['rel_class_user']."`
			WHERE user_id = ".$userId;
	$data = claro_sql_query_fetch_all_rows($sql);
	if (count($data))
	{
		foreach ($data as $classeUser)
		{
			$listeClasseUser[] = $classeUser['class_id'];
		}
	}
	
	return $listeClasseUser;
}


function UDADOCclaro_html_document_breadcrumb($curDirPath)
{
    $curDirPathList = explode('/', $curDirPath);

    $urlTrail = '';

    $breadcrumbNameList = array();
    $breadcrumbUrlList  = array();

    foreach($curDirPathList as $thisDir)
    {
        if ( empty($thisDir) )
        {
            $breadcrumbNameList[] = get_lang('Root');
            $breadcrumbUrlList[]  = '?cmd=exChDir&amp;file=';
        }
        else
        {
            $breadcrumbNameList[] = $thisDir;
            $urlTrail .= '/'.$thisDir;
            $breadcrumbUrlList[] = $_SERVER['PHP_SELF']
                                 . '?cmd=exChDir&amp;file='.rawurlencode($urlTrail);
        }
    }

    // remove the url on the last (current) element
    $breadcrumbUrlList[ count($breadcrumbUrlList) - 1] = null;

    return UDADOCclaro_html_breadcrumbtrail($breadcrumbNameList, $breadcrumbUrlList);
}

function UDADOCclaro_html_breadcrumbtrail($nameList, $urlList, $separator = ' &gt; ', $homeImg = null)
{
    // trail of only one element has no sense ...
    if (count ($nameList) < 2 ) return '<div class="breadcrumbTrail">&nbsp;</div>';

    $breadCrumbList = array();

    foreach($nameList as $thisKey => $thisName)
    {
        if (   array_key_exists($thisKey, $urlList)
        && ! is_null($urlList[$thisKey])       )
        {
            $startAnchorTag = '<a href="' . $urlList[$thisKey] . '" >';
            $endAnchorTag   = '</a>';
        }
        else
        {
            $startAnchorTag = '';
            $endAnchorTag   = '';
        }

        $htmlizedName = is_htmlspecialcharized($thisName)
        ? $thisName
        : htmlspecialchars($thisName);

        $breadCrumbList [] = $startAnchorTag
        . $htmlizedName
        . $endAnchorTag;
    }

    // Embed the last bread crumb entry of the list.

    $breadCrumbList[count($breadCrumbList)-1] = '<strong>'
    .end($breadCrumbList)
    .'</strong>';

    return  '<div class="breadcrumbTrail">'
    . ( is_null($homeImg) ? '' : '<img src="' . $homeImg . '" alt=""> ' )
    . implode($separator, $breadCrumbList)
    . '</div>';
}
?>
